/*
 *  Clase para hacer llamadas ajax
 *  *************************************************************************************************************************
 **/

function Request(){}

/**
 * Efectua llamadas ajax, validando que la respuesta JSON
 * posea argumento seccuess:true dentro de su cuerpo.
 * @returns Event Callback success
 * @receive Object
 * -url
 * -data (to POST)
 * -success callback
 * -error callback
 */

Request.prototype.request = function(config){
    jQuery.ajax({
        url: config.url,
        data:config.data,
        type:'POST',
        success: function(data) {
            if(data!==null){
                if(data.success || data){
                    if(config.success){
                        config.success(data);
                    }
                }
            }
        },
        error:function(data){
            if(config.error){
                config.error(data);
            }
        },
        dataFilter:function(dataType){
            return dataType;
        }
    });
};



/**
 * Clase core de Rocket
 */

function core(){

}


//core.prototype.beautyForms = true;

/**
* Identificador unico para cada objeto
* @receive {integer} el id
*/
core.prototype.id = '';

/**
* Permite setear si un objeto Rocket ya ha sido creado
* @receive {boolean} true o false
*/
core.prototype.isCreated = false;
/*
 * Define si se usara el plugin para homogenizar los formularios y sus elementos
 */
//core.prototype.setBeautyForms = function(beauty){
//    this.beautyForms = beauty;
//}
/*
 * Retorna TRUE/FALSE en caso de que se este usando beautyForms
 */
//core.prototype.getBeautyForms = function(){
//    return this.beautyForms;
//}


/**
* Permite retornar un string con el id tipo jquery '#identificador'
* @receive {string} textid: identificador ah parsear
* @return {string} nombre de id usando jquery
*/
core.prototype.getId = function(textid){
    return "#"+textid;
}

/**
* Permite retornar un id unico
* @return {string} identificador unico
*/
core.prototype.uniqueId = function(){
    var rand = Math.floor(Math.random() * 2000);
    return "Rocket-"+rand+""+(new Date()).getTime();
}

/**
* Permite conocer si un string o objeto es vacio
* @receive {string||object} string u objeto a evaluar
* @return {boolean} @true en caso de vacio, @false en caso contrario
*/
core.prototype.is_empty = function(val){
    if(val.lenght === 0 || jQuery.isEmptyObject(val) || val==="")
        return true;
    else return false;
};

///**
//* Permite conocer si un string o objeto es vacio
//* @return {boolean} @true en caso de vacio, @false en caso contrario
//*/
//core.prototype.setIdToForm = function(data,id){
//    var i=data.indexOf('<form');
//    if(i!=-1){//el formulario existe en la variable de texto
//        var idText = '<form id="'+id+'" ';
//
//        // console.log(idText);
//
//        data = idText+' '+data.substring(5, data.length);
//    }
//    return data;
//};

/**
* Arreglo de elementos creados durante la ejecucion de la libreria
* @receive {Array} de Element
*/
core.prototype._rocketItems = [];


/**
* Permite obtener un objeto Rocket usando su id
* @receive {string} id: identificador del objeto
* @return {Element|Panel|Grid|Dialog}
*/
core.prototype.get = function(id){
    var res;
    jQuery.each(this._rocketItems, function(i,item){
        if(item.id === id){
            res = item;
            return false;
        }
    });
    return res;
};

core.prototype.getMonthNameByNumber = function(i){
    var res = "";
    switch(i){
        case "01": res = 'Enero';break;
        case "02": res = 'Febrero';break;
        case "03": res = 'Marzo';break;
        case "04": res = 'Abril';break;
        case "05": res = 'Mayo';break;
        case "06": res = 'Junio';break;
        case "07": res = 'Julio';break;
        case "08": res = 'Agosto';break;
        case "09": res = 'Septiembre';break;
        case "10": res = 'Octubre';break;
        case "11": res = 'Noviembre';break;
        case "12": res = 'Diciembre';break;
    }
    return res;
}

core.prototype.parseDateString = function(String_date){
    var strDate = String_date;
    var dateParts = strDate.split(" ");
    var res = {
        year:dateParts[0].substring(0, 4),
        month:this.getMonthNameByNumber(dateParts[0].substring(5,7)),
        day:dateParts[0].substring(8,10),
        hour:dateParts[1].substring(0,2),
        minute:dateParts[1].substring(3,5),
        second:dateParts[1].substring(6,8)
    };
    return res;
}

//
//core.encode = function(object){
//    return $.toJSON( object );
//}


/**
 * Clase Rocket
 */
Rocket = new core();



/**
 * Clase Element
 */
Element.prototype = new core();


Element.prototype.constructor = Element;

function Element(){}

/**
* Valor desplegable que tiene el objeto Element, tiende ah ser el mismo
* al de un objeto de formulario comun y corriente
*/
Element.prototype.value = '';
/**
* Identificador del elemento
*/
Element.prototype.id = '';
/**
* Tipo de elemento
* -text
* -select-
* -textarea
* -radiogroup
* -buttongroup
* -password
* -datefield
*/
Element.prototype.type='';
/**
* Identificador del tag html donde se dibujara el elemento
*/
Element.prototype.renderTo='';
/**
* Atributo name usado en los objetos del formulario
*/
Element.prototype.name='';
/**
* Etiqueta asociada al elemento de formulario
*/
Element.prototype.label='';
/**
* Width asociado al elemento
*/
Element.prototype.width = '';
/**
* Height asociado al elemento
*/
Element.prototype.height = '';

Element.prototype.layoutOrientation = 'vertical';
/**
* En caso de poseer items como un select statico,
* esta propiedad permite definirlos
*/
Element.prototype.fields = [];

/**
* Style CSS usado por el elemento
*/
Element.prototype.style = '';

/**
* Nombre de clase usada por el elemento para dibujar un icono
*/
Element.prototype.iconCls = '';
/**
* Formato usado por los elementos de tipo 'datefield'
*/
Element.prototype.dateFormat = 'dd-mm-yy';
/**
* Objeto que hace referecia al padre contenedor del objeto actual
*/
Element.prototype.parentNode ={};
/**
* Permite configurar si es vivislbe o no el objeto
*/
Element.prototype.show = false;
/**
* Permite saber si un objeto ya ha sido dibujado
*/
Element.prototype.rendered = false;
/**
* Permite configurar si un elemento de tipo select
* se cargara en forma automatica al iniciarse
*/
Element.prototype.autoLoad = false;
/**
* Objeto que permite configurar proxy usado
* por los elementos de tipo select
*/
Element.prototype.proxy = [];
/**
* Callback ante evento 'change' del elemento
*/
Element.prototype.change = {};
/**
* Indice del array rocketItems
*/
Element.prototype.indexList = -1;
/**
* Nombre del campo que sera usado como indice(value)
* en un elemento de tipo 'select'
*/
Element.prototype.dataIndex = '';
/**
* Nombre del campo que sera mostrado en el elemento 'select'
*/
Element.prototype.dataField = '';
/**
* Array de Modelos que posee un elemento de tipo 'select'
*/
Element.prototype.modelItems = [];


Element.prototype._uid = '';


Element.prototype.disabled = false;


//Element.prototype.store = {};

/**
* Nombre del campo que sera usado como indice en un elemento de tipo 'select'
*/
Element.prototype.formatSizeStyle = function(size){
    var res_size= size;
    if(size.indexOf('%')=="-1" && size.indexOf('px')=="-1"){
        res_size = size+'px';
    }
    return res_size;
}


Element.prototype.setWidth = function(width){
    this.width = width;
    var eid = this.getId(this.id);

    if(this.type === 'select')  eid = jQuery(eid).next();

    width = this.formatSizeStyle(width);
    jQuery(eid).css('width',width);
};




Element.prototype.setHeight = function(height){
    this.height = height;
    var eid = this.getId(this.id);
    if(this.type === 'select')  eid = jQuery(eid).next();
    height = this.formatSizeStyle(height);
    jQuery(eid).css('height',height);
};



Element.prototype.setRenderTo = function(render){
    if(render!==''){
        this.renderTo = render;
    }
};
Element.prototype.render = function(){
    if(!this.rendered){
        var eid = this.getId(this.renderTo);
        this.create(this);
    }
};
Element.prototype.getWidth = function(){
    return this.width;
};
Element.prototype.getHeight = function(){
    return this.height;
};

Element.prototype.ready = false;


Element.prototype.addClickEvents= function(){
    var eid = this.getId(this.id);
    var _this = this;
    jQuery(eid).click(function(){
        if(_this.handler){
            _this.handler();
        }
    });
};

Element.prototype.addClickButtonSetEvent = function(){
    var classButtonset = '#'+this.id+' input';

    var _this = this;
    jQuery(classButtonset).click(function(){
        if(_this.handler){
            _this.handler({
                id:jQuery(this).attr('id'),
                value:jQuery(this).val(),
                label:jQuery(this).attr('label'),
                name:jQuery(this).attr('name')
            });
        }
    });
}
Element.prototype.addSelectEvents= function(){
    var eid = this.getId(this.id);
    var self = this;
    switch(this.type){
        case "select":
            jQuery(eid).change(function(a,b) {
                var modelId = jQuery(eid).attr('idSelected');
                var record = self.modelItems[modelId].row;
                self.change(record, self);
            });
            break;
        case "text":
            //   console.log('aqui')
            jQuery(eid).keyup(function() {
                self.change(jQuery(eid).val(),self);
            });
            break;
    }
};


/*
 *  Metodo que permite setear el valor de cada Element
 */
Element.prototype.set= function(value,extraParam){
    var eid = this.getId(this.id);
    var item = {};
    var _this = this;
    switch(this.type){
        case 'label':
            jQuery(eid).html(value);
            break;
        case 'image':
            jQuery(eid+'-image').attr('src',value);
            jQuery(eid+'-valueField').val(value);
            break;
        case 'text':
            jQuery(eid).val(value);
            break;
        case 'button':
            jQuery(eid).val(value);
            break;
        case 'datefield':
            jQuery(eid).val(value);
            break;
        case 'hidden':
            jQuery(eid).val(value);
            break;
        case 'password':
            jQuery(eid).val(value);
            break;
        case 'textarea':
            jQuery(eid).val(value);
            break;
        case 'select':
            var cbItems = this.modelItems;
            var _this = this;
            var changed = false;
            jQuery.each(cbItems,function(i,item){
                model = item.row;
                if(value === model.get(_this.dataIndex)){
                    _this.setSelectedItem(i);
                    changed = true;
                    return;
                }
            });
            if(!changed){
                var uid = _this.getId(_this.uid);
                var selectId = _this.getId(_this.id);
                var selectId = jQuery(uid+' input');

                jQuery(selectId).attr('textSelected','');
                jQuery(selectId).attr('idSelected','');

                jQuery(uid+' input').val('');

            }
            break;
        case 'buttonset':
            var classButtonset = this.getId(this.id);
            var checks = jQuery(classButtonset+' input');
            jQuery.each(checks,function(i,check){
                if(jQuery(check).attr('name') === value){
                    jQuery(check)[0].checked = extraParam;
                }
                jQuery(check).button('refresh');
            });
            break;
        case 'radiogroup':
            var classButtonset = this.getId(this.id);
            var radios = jQuery(classButtonset+' input');
            jQuery.each(radios,function(i,radio){
                if(jQuery(radio).val() === value){
                    jQuery(radio)[0].checked = true;
                }
                else{
                    jQuery(radio)[0].checked = false;
                }
                jQuery(radio).button('refresh');
            });
            break;
    }
    return item;
};


/**********************************************************************************************************
 *  metodos de acceso a los datos de cata objeto tipo Element
 **********************************************************************************************************
*/

/*
 *  Metodo que retorna un objeto con los datos del elemento
 */
Element.prototype.val= function(){
    var eid = this.getId(this.id);
    var item = {};
    var _this = this;
    switch(this.type){
        case 'text':
            item = {
                name:this.name,
                value:jQuery(eid).val()
            };
            break;
        case 'image':
            item = {
                name:this.name,
                value:jQuery(eid+'-valueField').val()
            };
        break;
        case 'hidden':
            item = {
                name:this.name,
                value:jQuery(eid).val()
            };
            break;
        case 'password':
            item = {
                name:this.name,
                value:jQuery(eid).val()
            };

            break;
        case 'textarea':
            item = {
                name:this.name,
                value:jQuery(eid).val()
            };
            break;
        case 'select':
            var record = this.getSelectedItem();
            var data = '';
            if(record)    data = record.get(this.dataIndex);
            item = {
                name:this.name,
                value:data
            };
            break;
        case 'buttonset':
            var classButtonset = this.getId(this.id);
            var res  = [];
            var pressed = 'off';
            jQuery.each(jQuery(classButtonset+' label'), function(i,item){
                id = _this.getId(jQuery(item).attr("for"));
                if(jQuery(item).attr('aria-pressed') === 'true') pressed = 'on';
                else    pressed = 'off';
                res.push({
                    name:jQuery(id).attr('name'),
                    value:pressed
                });
            });
            item = res;
            break;
        case 'radiogroup':
            var classButtonset = this.getId(this.id);
            var checked = jQuery(classButtonset).find('label[aria-pressed|="true"]');
            id = _this.getId(jQuery(checked).attr("for"));
            item = {
                name:jQuery(id).attr('name'),
                value:jQuery(id).val()
            };
            break;
        case 'datefield':
            item = {
                name:this.name,
                value:jQuery(eid).val()
            };
            break;
    }
    return item;
};
/*
 *  Metodo que retorna el modelo asociado a un item de un combobox
 */
Element.prototype.getSelectedItem= function(){
    var eid = this.getId(this.id);
    var modelId = jQuery(eid).attr('idSelected');
    var res = null;
    if(modelId && parseInt(modelId)>=0){
        if(this.modelItems[modelId])
            res = this.modelItems[modelId].row;
    }
    else res = null;
    return res;
};

Element.prototype.hasElements = function(){
    if(this.modelItems[0] && this.modelItems[0].row && this.modelItems.length>0)
        return true;
    else    return false;
}

/*
 *  Metodo que retorna el modelo asociado a un item de un combobox
 */
Element.prototype.getItemByIndex= function(index){
    return this.modelItems[index].row;
};
/*
 *  Metodo que setea un item de un combobox como seleccionado
 */
Element.prototype.setSelectedItem= function(index){
    if(this.modelItems[index] && this.modelItems.length>0){
        var model = this.modelItems[index].row;
        var value = model.get(this.dataField);
        jQuery(this.getId(this.id)).attr('textSelected', value);
        jQuery(this.getId(this.id)).attr('idSelected', index);
        jQuery(this.getId(this.id)).next().val(value);
    }
};

Element.prototype.changeEvent = function(){
    var eid = this.getId(this.id);
    var self = this;
    if(this.change.length){
        switch(this.type){
            case "select":
                jQuery(eid).change(function(a,b) {
                    var modelId = jQuery(eid).attr('idSelected');
                    var record = self.modelItems[modelId].row;
                    self.change(record, self);
                });
                break;
            case "textarea":
                jQuery(eid).keyup(function() {
                    self.change(jQuery(eid).val(),self);
                });
                break;
            case "text":
                jQuery(eid).keyup(function() {
                    self.change(jQuery(eid).val(),self);
                });
                break;
            case "buttonset":
                jQuery(eid+' input').click(function() {
                    self.change(self.val(),self);
                });
                break;
            case "radiogroup":
                jQuery(eid+' input').click(function() {
                    self.change(self.val(),self);
                });
                break;
        }
    }
}

/*
 **********************************************************************************************************
 */

Element.prototype.getHiddenInputString = function(){
    return '<input id="'+this.id+'" name="'+this.name+'" value="'+this.value+'" type="hidden"/>';
}

Element.prototype.getButtonString = function(){
    return '<button id="'+this.id+'" name="'+this.id+'" value="'+this.value+'" type="button">'+this.value+'</button>';
};
Element.prototype.getTextInputString = function(){
    return '<input class="text_align_left" id="'+this.id+'" name="'+this.name+'" value="'+this.value+'" type="text"/>';
};
Element.prototype.getPasswordInputString = function(){
    return '<input class="text_align_left" id="'+this.id+'" name="'+this.name+'" value="'+this.value+'" type="password"/>';
};
Element.prototype.getTextAreaString = function(){
    return '<textarea class="text_align_left" id="'+this.id+'" name="'+this.name+'" value="'+this.value+'">'+this.value+'</textarea>';
};
Element.prototype.getLabelStringFor = function(){
    return '<label class="rck_panel_label" for="'+this.name+'">'+this.label+'</label>';
};

Element.prototype.getValidationItem = function(){
    return '<div rck_validation_name="'+this.name+'" id="'+this.id+'-validation" class="rck_element_validation"></div>';
};

Element.prototype.getLabelString = function(){
    return '<label name="'+this.name+'" id="'+this.id+'">'+this.text+'</label>';
};

Element.prototype.getImageString = function(){
    var imgSrc = '';
    if(this.src)    imgSrc = ' src="'+this.src+'" ';
    return '<ul style="float:left;"><li><input name="'+this.uploadName+'" id="'+this.id+'-fileInput" style="float:left;" type="file" value="'+this.src+'"/><input id="'+this.id+'-uploadButton" style="float:left;" type="button" value="Subir"/></li><li><a id="'+this.id+'-lnkAction" href="javascript:void(0);" ><img '+imgSrc+' id="'+this.id+'-image"/></a></li><input name="'+this.name+'" id="'+this.id+'-valueField" type="hidden" value="'+this.src+'"/></ul>';
};

Element.prototype.getButtonSetString = function(){
    var txt = '<div id="'+this.id+'">';
    var _this = this;
    var _class = 'rck_buttonset_click-'+this.id;
    jQuery.each(this.fields, function(i, item){
        check = '';
        if(item.checked) check = ' checked="checked"';
        id = _this.id+'-'+i;
        txt = txt+'<input name="'+item.name+'" id="'+id+'" label="'+item.text+'" type="checkbox" '+check+' /><label for="'+id+'">'+item.text+'</label>';
    });
    txt = txt+'</div>';
    return txt;
};
Element.prototype.getRadioGroupString = function(){
    var txt = '<div class="rck_panel_element_buttonset" id="'+this.id+'">';
    var _this = this;

    jQuery.each(this.fields, function(i, item){
        check = '';
        if(item.checked) check = ' checked="checked"';
        id = _this.id+'-'+i;
        txt = txt+'<input type="radio" name="'+item.name+'" value="'+item.value+'" id="'+id+'" label="'+item.text+'"'+check+'  /><label for="'+id+'">'+item.text+'</label>';
    });
    txt = txt+'</div>';
    return txt;
};

Element.prototype.getSelectContainer = function(){
    return '<select style="display:none;'+this.style+'" name="'+this.name+'" id="'+this.id+'" textSelected="" idSelected="">';
}

Element.prototype.getSelectOptions = function(){
    var options = '';
    var _this = this;
    _this.modelItems = [];
    if(this.fields.length>0){
        jQuery.each(this.fields, function(i,item){
            _this.modelItems[i] = {
                i:i,
                row:new Model(item)
            };
            options = options+'<option idList="'+i+'" value="'+item[_this.dataIndex]+'">'+item[_this.dataField]+'</option>';
        });
    }
    return options;
}

Element.prototype.getSelectString = function(){
    var sel = '<select name="'+this.name+'" id="'+this.id+'" textSelected="" idSelected="">';
    var selEnd = '</select>';
    var selId = this.getId(this.id);
    var options = '';
    var _this = this;

    if(_this.indexList<0) _this.indexList++;
    i = _this.indexList;
    _this.modelItems = [];
    jQuery.each(this.fields, function(index,item){
        if(item[_this.dataIndex]){
            value = item[_this.dataIndex];
            text = item[_this.dataField];
            options = options+'<option idList="'+i+'" value="'+value+'">'+text+'</option>';
            _this.modelItems[i] = {
                i:i,
                row:new Model(item)
            };
            i++;
        }
    });
    _this.indexList = _this.modelItems.length;
    return sel+options+selEnd;
};

Element.prototype.load = function(cfg){
    var _this = this;
    var eid = this.getId(this.id);
    var renderTo = this.getId(this.renderTo);
    var classes = "rck_panel_element";
    var http = new Request();
    http.request({
        url:_this.proxy.url,
        data:cfg,
        success:function(data){
            if(_this.beforeSuccess){
                _this.beforeSuccess(data);
            }
            _this.fields = data.rows;

            jQuery(eid).html('');
            jQuery(eid).append(_this.getSelectOptions());

            if(_this.afterSuccess){
                _this.afterSuccess(data);
            }
        }
    });
};
Element.prototype.getDisabled = function(){
    return this.disabled;
}
Element.prototype.setDisabled = function(disabled){
    var eid = this.getId(this.id);
    switch(this.type){
        case "button":jQuery(eid).button( "option", "disabled", disabled );break;
        case "buttonset":
            if(disabled)    jQuery(eid).buttonset("disable") ;
            else            jQuery(eid).buttonset("enable") ;
        break;
        case "radiogroup":
            if(disabled)    jQuery(eid).buttonset("disable") ;
            else            jQuery(eid).buttonset("enable") ;
        break;
        case "text":jQuery(eid).button({disabled:disabled});break;
        case "datefield":jQuery(eid).datepicker( "option", "disabled", disabled );break;
        case "password":jQuery(eid).button({disabled:disabled});break;
        case "textarea":jQuery(eid).button({disabled:disabled});break;
        case "select":
            if(disabled)    jQuery(eid).combobox("disable");
            else            jQuery(eid).combobox("enable");
        break;
    }
    this.disabled = disabled;
}

Element.prototype._init = function(cfg){
    if(cfg.value) this.value = cfg.value;
    if(cfg.id) this.id = cfg.id;
    if(cfg.type) this.type = cfg.type;
    if(cfg.renderTo) this.renderTo= cfg.renderTo;
    if(cfg.handler) this.handler= cfg.handler;
    if(cfg.name) this.name= cfg.name;
    if(cfg.label) this.label= cfg.label;
    if(cfg.width) this.width= cfg.width;
    if(cfg.height) this.height= cfg.height;

    if(cfg.iconCls) this.iconCls= cfg.iconCls;
    if(cfg.style) this.style= cfg.style;

    if(cfg.collapsed) this.collapsed= cfg.collapsed;
    if(cfg.collapsible) this.collapsible= cfg.collapsible;
    if(cfg.draggable) this.draggable= cfg.draggable;

    if(cfg.proxy) this.proxy= cfg.proxy;
    if(cfg.fields) this.fields= cfg.fields;
    if(cfg.change) this.change= cfg.change;
    if(cfg.dataIndex) this.dataIndex= cfg.dataIndex;
    if(cfg.dataField) this.dataField= cfg.dataField;

    if(cfg.parentNode) this.parentNode = cfg.parentNode;

    if(cfg.title) this.title= cfg.title;
    if(cfg.dateFormat) this.dateFormat= cfg.dateFormat;
    if(cfg.autoLoad) this.autoLoad= cfg.autoLoad;
    if(cfg.beforeSuccess) this.beforeSuccess= cfg.beforeSuccess;
    if(cfg.afterSuccess) this.afterSuccess= cfg.afterSuccess;

    if(cfg.disabled) this.disabled= cfg.disabled;
    if(cfg.text) this.text= cfg.text;
    if(cfg.src) this.src= cfg.src;
    
    if(cfg.uploadFileAction) this.uploadFileAction= cfg.uploadFileAction;
    if(cfg.uploadName) this.uploadName= cfg.uploadName;

    this.isCreated = true;
}

Element.prototype.create = function(cfg){

    if(!this.isCreated) this._init(cfg);
    var _this = this;

    var eid = this.getId(this.id);
    var renderTo = this.getId(this.renderTo);

    var classes = "rck_panel_element";
    var classesImg = 'rck_panel_element_image';

    if(this.layoutOrientation === 'horizontal'){
        classes = classes+' rck_panel_horizontalLayout';
    }


    if(this.renderTo!==''){
        switch(this.type){
            case "button":
                jQuery(renderTo).append(this.getButtonString());
                this.addClickEvents();

                if(this.iconCls && this.iconCls!==''){
                    jQuery(eid).button({
                        icons:{
                            primary:this.iconCls
                        }
                    });
                }
                else    jQuery(eid).button();
                break;
            case "buttonset":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getLabelStringFor()+this.getButtonSetString()+'</div>');
                jQuery(eid).buttonset();
                jQuery(renderTo).append(this.getValidationItem());
                break;
            case "radiogroup":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getLabelStringFor()+this.getRadioGroupString()+'</div>');
                jQuery(eid).buttonset();
                jQuery(renderTo).append(this.getValidationItem());
                break;
            case "label":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getLabelString()+'</div>');
                break;
            case "text":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getLabelStringFor()+this.getTextInputString()+'</div>');
                jQuery(eid).button();
                jQuery(renderTo).append(this.getValidationItem());
                break;
            case "datefield":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getLabelStringFor()+this.getTextInputString()+'</div>');
                jQuery(eid).button();
                jQuery(eid).datepicker({
                    dateFormat:'yy-mm-dd',
                    changeMonth: true,
                    changeYear: true
                });
                jQuery(renderTo).append(this.getValidationItem());
                break;
            case "hidden":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getHiddenInputString()+'</div>');
                break;
            case "image":
                var btnAction = this.getId(this.id+'-uploadButton');
                var image = this.getId(this.id+'-image');
                var fileInput = this.id+'-fileInput';
                
                jQuery(renderTo).append('<div class="'+classes+' '+classesImg+'">'+this.getLabelStringFor()+this.getImageString()+'</div>');
                
                jQuery(btnAction).click(function(){
                    $.ajaxFileUpload({
                        url:_this.uploadFileAction,
                        secureuri:false,
                        fileElementId:fileInput,
                        dataType: 'json',
                        success: function (data, status)
                        {
                            if(typeof(data.error) != 'undefined')
                            {
                                if(data.error != '')
                                {
                                    alert(data.msg);
                                }else
                                {
                                    //_this.set(data.path);
                                    _this.handler(data);
                                }
                            }
                        },
                        error: function (data, status, e)
                        {
                            alert(e);
                        }
                    });
                    return false;
                });
                /*
                var lnkAction = this.getId(this.id+'-lnkAction');
                var image = this.getId(this.id+'-image');
                var valueField = this.getId(this.id+'-valueField');
                jQuery(renderTo).append('<div class="'+classes+' '+classesImg+'">'+this.getLabelStringFor()+this.getImageString()+'</div>');
                jQuery(lnkAction).click(function(){
                    if(_this.handler){
                        _this.handler(jQuery(valueField).val());
                    }
                    else{
                        return;
                    }
                });
                */
                jQuery(renderTo).append(this.getValidationItem());
                break;
            case "password":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getLabelStringFor()+this.getPasswordInputString()+'</div>');
                jQuery(eid).button();
                jQuery(renderTo).append(this.getValidationItem());
                break;
            case "textarea":
                jQuery(renderTo).append('<div class="'+classes+'">'+this.getLabelStringFor()+this.getTextAreaString()+'</div>');
                jQuery(eid).button();
                jQuery(renderTo).append(this.getValidationItem());
                break;
            case "select":
                var uid = this.uniqueId();
                if(this.fields.length>0){
                    jQuery(renderTo).append('<div id="'+uid+'" style="'+this.style+'" class="'+classes+'">'+this.getLabelStringFor()+this.getSelectString()+'</div>');
                    jQuery(eid).combobox();
                    _this.setSelectedItem(0);
                    
                }
                else{
                    this.uid = uid;
                    var selectId = _this.renderTo+'-select';
                    jQuery(renderTo).append('<div style="'+this.style+'"  id="'+uid+'">'+_this.getLabelStringFor()+_this.getSelectContainer()+'</div>');
                    jQuery(eid).combobox();
                    if(_this.proxy && this.autoLoad){
                        _this.load();
                    }
                }
                jQuery(renderTo).append(this.getValidationItem());
                break;
        }

        this.rendered = true;
    }

    var curStyle = jQuery(eid).attr('style');
    if(curStyle)    jQuery(eid).attr('style',curStyle+' '+this.style);
    else            jQuery(eid).attr('style',this.style);

    this.changeEvent();

    this.setWidth(this.width);
    this.setHeight(this.height);

    this.setDisabled(this.disabled);


    this._rocketItems.push(this);
    return this;
};

/*
 *  Clase Panel
 *  *************************************************************************************************************************
 **/


Panel.prototype = new Element();
Panel.prototype.constructor = Panel;
function Panel(){}

Grid.prototype = new Panel();
Grid.prototype.constructor = Grid;
function Grid(){}

Layout.prototype = new Panel();
Layout.prototype.constructor = Layout;
function Layout(){}

Panel.prototype.collapsible = false;
Panel.prototype.collapsed = false;
Panel.prototype.modal = false;
Panel.prototype.draggable = false;
Panel.prototype.isInner = false;
Panel.prototype.parentContainerId = '';
Panel.prototype.title = '';


Panel.prototype.childs = '';


Panel.prototype.width = '';
Panel.prototype.height = '';

Panel.prototype.headerToolbar = [];
Panel.prototype.items = [];
Panel.prototype.buttons = [];
Panel.prototype.footerToolbar = [];

Panel.prototype.panelId = '';
Panel.prototype.buttonsPanelId = '';

Panel.prototype.layout = 'vertical';

Panel.prototype.isForm = false;


Panel.prototype.html = '';
Panel.prototype.modal = false;

Panel.prototype.bodyStyle = '';

Panel.prototype.setTitle = function(title){
    var toggleId = this.renderTo+'-toggle';
    var eid = this.getId(this.renderTo);
    jQuery(eid+' .rck_panel_title').append('<a href="javascript:void(0);" id="'+toggleId+'" class="ui-dialog-title">'+title+'</a> ')
};
/**
 * @link por definir...
 * @param String title <p>
 * Nuevo titulo para el panel
 * </p>
 */
Panel.prototype.setTitleDialog = function(title){
    jQuery(this.getId(this.renderTo)).dialog('option','title',title);
}

/**********************************************************************************************************
 *  metodos de acceso a los datos de cata objeto tipo Element contenido en el panel form
 **********************************************************************************************************
*/

/*
 *  Metodo que retorna los datos de todos los campos de un formulario exceptuando botones
 */
Panel.prototype.getValues= function(){
    var eid = this.getId(this.id);
    var _this = this;
    var res = [];
    if(this.type === 'panel'){
        jQuery.each(this.childs, function(i,item){
            if(item.type !== 'button' && item.type !== 'panel' && item.type !== 'grid' && item.type !== 'label'){
                tmp = item.val();
                if(tmp!==null)
                    res.push(tmp);
            }
            else{
                if(item.type === 'panel'){
                    tmp2 = item.getValues();
                    if(tmp2.length>0)
                        res.push(tmp2);
                }
            }
        });
    }
    return res;
};

Panel.prototype.toFormPost= function(data){
    var res = [];
    var _this = this;
    jQuery.each(data,function(i,item){
        if(item.length){//si es array repetimos el proceso
            res = jQuery.merge(res,_this.toFormPost(item));
        }
        else{//solo cuando es objeto lo pasamos al array
            res.push(item);
        }
    });
    return res;
}

Panel.prototype.cleanValidation= function(){
    var renderTo = this.getId(this.renderTo);
    jQuery(renderTo+ ' .rck_element_validation').css('display','none');
}

Panel.prototype.validateForm= function(errors){
    var renderTo = this.getId(this.renderTo);
    var childs = jQuery(renderTo+ ' .rck_element_validation');
    var _this = this;
    var error = false;
    jQuery.each(childs,function(k,child){
        jQuery.each(errors, function(i,item){
            if(jQuery(child).attr('rck_validation_name') === i){
                jQuery(child).text(item);
                jQuery(child).slideDown('slow');
                error = true;
            }
        });
        if(!error)   {
            jQuery(child).text('');
            jQuery(child).slideUp('fast');
        }
        error = false;
    });
}

Panel.prototype.submit= function(postData){
    var _this = this;
    var datax;
    if(postData && postData.data) datax = postData.data;
    else    datax = _this.getValues();
    datax = _this.toFormPost(datax);
    if(this.proxy){
        var http = new Request();
        http.request({
            url:_this.proxy.url,
            method:'POST',
            data:datax,
            success:function(data){
                if(postData.beforeSuccess){
                    postData.beforeSuccess(data);
                }

                if(data){
                    _this.validateForm(data.errors);
                    postData.success(data);
                }
                else{
                    _this.validateForm(data.errors);
                    if(postData.error){
                        postData.error(data);
                    }
                }

                if(postData.afterSuccess){
                    postData.afterSuccess(data);
                }
            }
        });

    }
};

Panel.prototype.fillFormInputs= function(data){

    this.cleanForm();

    var data = data.data;
    var _this = this;
    var renderTo = this.getId(this.renderTo);
    var childs = jQuery(renderTo+ ' .rck_panel_element label');
    var _this = this;
    var setted = false;
    var n = 0;
    jQuery.each(this.childs,function(i,child){
        jQuery.each(data,function(name,value){
            if(child.name === name){
                child.set(value);
            }
            else{
                if(child.type === 'buttonset'){
                    child.set(name,true);
                }
            }
        });
    });
    return;
};



Panel.prototype.fill= function(postData){
    var _this = this;
    var datax;
    if(postData && postData.data) datax = postData.data;
    if(postData.proxy){
        var http = new Request();
        http.request({
            url:postData.proxy.url,
            method:'POST',
            data:datax,
            success:function(data){
                
           //     console.debug(data)
                
                
                if(postData.beforeSuccess){
                    postData.beforeSuccess(data);
                }

                if(data.success){
                    _this.fillFormInputs(data);
                    postData.success(data);
                }
                else{
                    if(postData.error){
                        postData.error(data);
                    }
                }

                if(postData.afterSuccess){
                    postData.afterSuccess(data);
                }
            }
        });

    }
};


Panel.prototype.getHtml = function(){
    return jQuery(this.getId(this.renderTo+'-elements')).html();
};

Panel.prototype.setHtml = function(html){
    jQuery(this.getId(this.renderTo+'-elements')).html(html);
};

Panel.prototype.append = function(html){
    jQuery(this.getId(this.renderTo+'-elements')).append(html);
};

Panel.prototype.buildContainers = function(){
    if(!this.renderTo){ //si no posee contenedor asociado
        this.renderTo = this.id;

        jQuery('body').append('<div id="'+this.renderTo+'"></div>');
    }
    var renderToId = this.getId(this.renderTo);
    //si es un panel interior pasamos como renderTo el id de elementos del panel superior
    if(this.isInner){
        renderToId = this.getId(this.parentContainerId+'-elements');
        this.renderTo = this.id;
    }

    var renderToElementsId = this.renderTo+'-elements';
    var renderToButtonsId = this.renderTo+'-buttons';

    var titleContainer = this.renderTo+'-titleContainer';


    var headerClasses = "rck_panel_title ui-dialog-titlebar ui-widget-header ui-corner-top ui-helper-clearfix";
    var contentClasses = "rck_panel_content ui-dialog-content ui-widget-content";

    var innerContentClasses = "rck_panel_content_elements";

    var buttonsClasses = "rck_panel_buttons ui-dialog-content ui-widget-content";

    if(!this.isInner){
     //   console.log(this.bodyStyle)

        jQuery(renderToId).append('<div id="'+ titleContainer +'" class="'+headerClasses+'">');
        jQuery(renderToId).append('<div style="'+this.bodyStyle+'" id="'+renderToElementsId+'" class="'+contentClasses+' '+innerContentClasses+'">');
        jQuery(renderToId).append('<div id="'+renderToButtonsId+'" class="'+buttonsClasses+'">');
    }
    else{
        var content = '<div id="'+ titleContainer +'" class="'+headerClasses+'"></div><div style="'+this.bodyStyle+'" id="'+renderToElementsId+'" class="'+contentClasses+' rck_elements"></div><div id="'+renderToButtonsId+'" class="'+buttonsClasses+'"></div>';
        jQuery(renderToId).append('<div style="'+this.style+'" id="'+this.renderTo+'" class="rck_panel_element">'+content+'</div>');
    }

    if(!this.buttons || this.buttons.length===0 ){
        jQuery(this.getId(renderToButtonsId)).css('display','none');
    }
    if(!this.title){
        jQuery(this.getId(titleContainer)).css('display','none');
    }

    //construimos link como titulo
    this.setTitle(this.title);

    if(this.isInner) renderToId = this.getId(this.renderTo);
    width = this.formatSizeStyle(this.width);
    jQuery(renderToId).css('width',width);
    
    var _this = this;
    

    var toggleButtonsId = this.getId(this.renderTo+'-buttons');
    var toggleElements = this.getId(renderToElementsId);
    var toggleToolbarId = this.getId(this.renderTo+'-toolbarContainer');

    if(this.collapsible){
        var toggleId = this.getId(this.renderTo+'-toggle');

        jQuery(toggleId).click(function(){
            
            _this.collapsed = !_this.collapsed;
            
            if(_this.onCollapsing){
                _this.onCollapsing(_this,_this.collapsed);
            }
            
            
            jQuery(toggleElements).toggle('slideUp');
            jQuery(toggleButtonsId).toggle('slideUp');
            jQuery(toggleToolbarId).toggle('slideUp');
        });
    }

    if(this.collapsed){
        jQuery(toggleElements).css('display','none');
        jQuery(toggleButtonsId).css('display','none');
        jQuery(toggleToolbarId).css('display','none');
    }

    if(!this.isInner){
        if(this.draggable){
            jQuery(renderToId).draggable();
        }
    }

}

Panel.prototype.create = function(cfg){
    if(!this.isCreated) this._init(cfg);
    if(cfg.items) this.items = cfg.items;
    if(cfg.buttons) this.buttons = cfg.buttons;
    if(cfg.isInner) this.isInner = cfg.isInner;
    if(cfg.parentContainerId) this.parentContainerId = cfg.parentContainerId;

    if(cfg.layout) this.layout = cfg.layout;
    if(cfg.html) this.html = cfg.html;
    if(cfg.modal) this.modal = cfg.modal;
    if(cfg.isForm) this.isForm = cfg.isForm;
    if(cfg.proxy) this.proxy = cfg.proxy;
    if(cfg.bodyStyle) this.bodyStyle = cfg.bodyStyle;
    if(cfg.title){
        this.title = cfg.title;
    }

    if(cfg.parentNode) this.parentNode = cfg.parentNode;
    
    
    if(cfg.onCollapsing) this.onCollapsing = cfg.onCollapsing;
    

    this.childs = [];

    var _this = this;
    var renderTo = this.getId(this.renderTo);

    //construimos div de cabecera, elementos y botones inferiores
    this.buildContainers();

    if(this.items && this.items.length>0){
        jQuery.each(this.items, function(index,item){
            if(item.type === 'panel'){
                item.isInner = true;
                item.parentContainerId = _this.renderTo;//div3
                item.renderTo = _this.renderTo+'-elements';
                item.parentNode = _this;
                var newItem = (new Panel()).create(item);

                _this.childs.push(newItem);

            }
            else{
                item.renderTo = _this.renderTo+'-elements';
                var newItem;
                if(item.type!=='panel' && item.type!=='grid'){
                    item.parentNode = _this;
                    newItem = (new Element()).create(item);
                }
                if(item.type==='grid'){
                    item.isInner = true;
                    item.parentContainerId = _this.renderTo;
                    item.parentNode = _this;
                    newItem = (new Grid()).create(item);
                }

                _this.childs.push(newItem);
            }
        });
    }
    if(this.buttons && this.buttons.length>0){
        jQuery.each(this.buttons, function(index,item){
            if(item.type==='button'){
                item.renderTo = _this.renderTo+'-buttons';
                item.parentNode = _this;
                var newItem = (new Element()).create(item);
            }

        });
    }
    if(!this.items || this.items.length === 0){
        if(jQuery(renderTo).html() !== ''){
            renderToElements = this.getId(this.renderTo+'-elements');
            html = jQuery(renderTo).html();
            jQuery(renderToElements).html(this.html);
        }
    }
    else{
        if(this.html && !this.is_empty(this.html)){
            renderToElements = this.getId(this.renderTo+'-elements');
            jQuery(renderToElements).html(this.html);
        }
    }
    


    var renderToId = this.getId(_this.renderTo);

    if(this.modal)  {
        jQuery(renderToId).dialog({
            autoOpen:false,
            title:this.title,
            modal:true,
            maxHeight:600,
            maxWidth:jQuery(this.getId(_this.renderTo)).width()+20,
            open: function(event, ui) {
                jQuery(this).css({
                    'max-height': 600,
                    'overflow-y': 'auto'/*,
                    'width':'100%'*/
                });
            },
            close:function(event,ui){
                _this.cleanForm();
            },
            width:jQuery(this.getId(_this.renderTo)).width()
        });
        jQuery(this.getId(_this.renderTo+'-titleContainer')).css('display','none');
    }
    this._rocketItems.push(this);
    return this;
}

Panel.prototype.show = function(){
    this.cleanValidation();
    var renderToId = this.getId(this.renderTo);
    if(this.modal){
        jQuery(renderToId).dialog('open');
    }
}

Panel.prototype.reloadCombos = function(){
    jQuery.each(this.childs, function(i,Element){
        if(Element.type === 'select'){
           // if(Element.af)
            Element.load();
        }
    });
}

Panel.prototype.close = function(){
    this.cleanForm();
    jQuery(this.getId(this.renderTo)).dialog('close');
};


Panel.prototype.cleanForm = function(){
    var _this = this;
    jQuery.each(this.childs,function(i,item){
        if(item instanceof Element){
            if(item.type === 'text' || item.type === 'textarea' ||  item.type === 'password' ||  item.type === 'datefield')
                jQuery(_this.getId(item.id)).val('');
            /*if(item.type === 'select'){
                item.setSelectedItem(0);
            }*/
            if(item.type === 'buttonset'){
                var checks = item.fields;
                jQuery.each(checks,function(i,check){
                    item.set(check.name,false);
                })
            }
        }
    });
}

Panel.prototype.resetForm = function(){
    var _this = this;
    jQuery.each(this.childs,function(i,item){
        if(item instanceof Element){
            if(item.type === 'text' || item.type === 'textarea' ||  item.type === 'password' ||  item.type === 'datefield' || item.type === 'hidden')
                jQuery(_this.getId(item.id)).val('');
            if(item.type === 'select'){
                //console.debug(item);
                item.setSelectedItem(0);
            }
            if(item.type === 'buttonset'){
                var checks = item.fields;
                jQuery.each(checks,function(i,check){
                    if(typeof check.checked !== 'undefined'){
                        item.set(check.name,true);
                    }
                    else{
                        item.set(check.name,false);
                    }
                })
            }
            if(item.type === 'radiogroup'){
                var checks = item.fields;
                jQuery.each(checks,function(i,check){
                    if(typeof check.checked !== 'undefined'){
                        item.set(check.value);
                    }
                })
            }
        }
    });
};





/************************************************************************************************************************/

/*
 *  Clase Grid
 *
 */

Grid.prototype.columns = [];
Grid.prototype.pageSize = 20;
Grid.prototype.autoLoad = false;
Grid.prototype.fit = false;
Grid.prototype.singleSelect = true;

Grid.prototype.itemClick = {};

Grid.prototype.sortorder = '';
Grid.prototype.sortname = '';

Grid.prototype.extraParams = {};

Grid.prototype.selectedItems = {};

Grid.prototype.searchitems = [];

/**
 * (PHP 4, PHP 5)<br/>
 * Find position of first occurrence of a string
 * @link http://php.net/manual/en/function.strpos.php
 * @param string $haystack <p>
 * The string to search in
 * </p>
 * @param mixed $needle <p>
 * If needle is not a string, it is converted
 * to an integer and applied as the ordinal value of a character.
 * </p>
 * @param int $offset [optional] <p>
 * The optional offset parameter allows you
 * to specify which character in haystack to
 * start searching. The position returned is still relative to the
 * beginning of haystack.
 * </p>
 * @return int the position as an integer. If needle is
 * not found, strpos will return boolean
 * false.
 */

Grid.prototype.load = function(cfg){
    var renderToGrid = this.getId(this.renderTo+'-grid');
    if(cfg){
        jQuery(renderToGrid).flexOptions({
            query: Rocket.encode(cfg)
        }).flexReload();
    }
    else{
        jQuery(renderToGrid).flexOptions({
            query: null
        }).flexReload();
    }
};

Grid.prototype.cleanQuery = function(cfg){
    var renderToGrid = this.getId(this.renderTo+'-grid');
    if(cfg){
        jQuery(renderToGrid).flexOptions({
            query: Rocket.encode(cfg)
        }).flexReload();
    }
    else{
        jQuery(renderToGrid).flexOptions({
            query: null
        }).flexReload();
    }
};

Grid.prototype.buildToolBar = function(){
    var titleContainer = this.getId(this.renderTo+'-titleContainer');
    var toolBarContainerId = this.renderTo+'-toolbarContainer';
    var toolBarClasses = "rck_panel_toolbar rck_panel_title ui-dialog-titlebar ui-widget-header ui-helper-clearfix";

    var renderToId = this.getId(toolBarContainerId);

    jQuery(titleContainer).after('<div id="'+ toolBarContainerId +'" class="'+toolBarClasses+'">');

    if(!this.toolbar || this.is_empty(this.toolbar)){
        jQuery(this.getId(toolBarContainerId)).css('display','none');
    }
};
Grid.prototype.buildGridContainer = function(){
    var renderTo = this.getId(this.renderTo+'-elements');
    var gridContainerId = this.renderTo+'-grid';
    jQuery(renderTo).append('<table id="'+ gridContainerId +'"></table>');
};

Grid.prototype.getSelectedItem = function(){
    var res = [];
    var _this = this;
    var renderTo = this.getId(this.renderTo);
    jQuery.each(jQuery(renderTo+' .trSelected'), function(i,item){
        var id = jQuery(item).attr('rowid');
        res.push(new Model(_this.selectedItems[id]));
    });
    return res;
}

Grid.prototype.setExtraParams = function(arrayParams){
    var renderToGrid = this.getId(this.renderTo+'-grid');
    if(arrayParams.length>0){
        jQuery(renderToGrid).flexOptions(
            {params: arrayParams});
    }
}

Grid.prototype.cleanExtraParams = function(){
    var renderToGrid = this.getId(this.renderTo+'-grid');
    jQuery(renderToGrid).flexOptions({params:null});
}

Grid.prototype.create = function(cfg){
    if(!this.isCreated) this._init(cfg);
    if(cfg.toolbar) this.toolbar = cfg.toolbar;
    if(cfg.buttons) this.buttons = cfg.buttons;
    if(cfg.isInner) this.isInner = cfg.isInner;
    if(cfg.parentContainerId) this.parentContainerId = cfg.parentContainerId;

    if(cfg.modal) this.modal = cfg.modal;
    if(cfg.proxy) this.proxy = cfg.proxy;
    if(cfg.autoLoad) this.autoLoad = cfg.autoLoad;
    if(cfg.columns) this.columns = cfg.columns;
    if(cfg.pageSize) this.pageSize = cfg.pageSize;
    if(cfg.fit) this.fit = cfg.fit;
    if(cfg.itemClick){
        this.itemClick = cfg.itemClick;
    }
    else{
        this.itemClick = function(){
        //throw 'Function itemClick in Grid not defined';
        }
    }

    if(cfg.sortname) this.sortname = cfg.sortname;
    if(cfg.sortorder) this.sortorder = cfg.sortorder;
    if(cfg.searchitems) this.searchitems = cfg.searchitems;

    if(cfg.extraParams) this.extraParams = cfg.extraParams;
    else this.extraParams = null;

    if(cfg.singleSelect) this.singleSelect = cfg.singleSelect;

    var _this = this;
    var renderTo = this.getId(this.renderTo);

    //construimos div de cabecera, elementos y botones inferiores
    this.buildContainers();
    this.buildToolBar();
    this.buildGridContainer();


    var renderToGrid = this.getId(this.renderTo+'-grid');
    var renderToElemenets = this.getId(this.renderTo+'-elements');
    jQuery(renderToElemenets).css('padding','0')

    if(this.toolbar && this.toolbar.length>0){
        jQuery.each(this.toolbar, function(index,item){
            if(item.type==='button' || item.type==='buttonset'){
                item.renderTo = _this.renderTo+'-toolbarContainer';
                item.parentNode = _this;
                var newItem = (new Element()).create(item);
            }

        });
    }

    if(this.fit){
        var nVisibleColumns = 0;
        jQuery.each(this.columns, function(i,item){
            if(!item.hide){
                nVisibleColumns++;
            }
        });
        var widthContainer = jQuery(this.getId(_this.renderTo)).width();
        var widthColumn = parseInt( widthContainer/nVisibleColumns)-14;

   //     console.log('width: '+widthContainer+', colmun: '+widthColumn);

        var res = [];
        if(this.columns && this.columns.length>0){
            jQuery.each(this.columns, function(i,item){
                item.width = widthColumn;
                res.push(item)
            });
            this.columns = res;
        }
    }
    jQuery(renderToGrid).flexigrid({
        searchitems:this.searchitems,
        sortorder:this.sortorder,
        sortname:this.sortname,
        url: this.proxy.url,
        dataType: 'json',
        colModel :this.columns,
        autoload:this.autoLoad,
        usepager: true,
        useRp: true,
        rp: this.pageSize,
        singleSelect:this.singleSelect,
        showTableToggleBtn: true,
        resizable:false,
        //width:1000,
        height: this.height||250,
        setClickedItem:function(item){
            _this.selectedItem = item;
            _this.itemClick(new Model(item));
        },
        renderTo:renderToGrid,
        getSelectedItem:function(items){
            _this.selectedItems = items;
        },
        params:this.extraParams
    });
    this._rocketItems.push(this);
    return this;
}

/*
 *
 *  Clase que permite definir un panel superior con 4 posiciones, norte,sur,este,oeste
 *
 */
Layout.prototype.buildLayoutSections = function(){
    var _this = this;
    if(!this.renderTo){ //si no posee contenedor asociado
        this.renderTo = this.id;
        jQuery('body').append('<div id="'+this.renderTo+'"></div>');
    }

    var renderToId = this.getId(this.renderTo);

    jQuery(renderToId).css('width','100%');
    jQuery(renderToId).css('height','100%');

    jQuery.each(this.items,function(i,item){
        var id = _this.id+'-'+item.orientation;
        var classOrientation = 'ui-layout-'+item.orientation;
        jQuery(renderToId).append('<div id="'+id+'" class="'+classOrientation+'"></div>');
    })
}

Layout.prototype.create = function(cfg){
    if(!this.isCreated) this._init(cfg);
    if(cfg.items) this.items = cfg.items;

    this.buildLayoutSections();
    var renderToId = this.getId(this.renderTo);

    jQuery(renderToId).layout();
}



Dialog.prototype = new Element();
Dialog.prototype.constructor = Dialog;
function Dialog(){}

Dialog.prototype.message = '';
Dialog.prototype.typeAlert = '';
Dialog.prototype.onOkHanlder = null;

Dialog.prototype.builButtons = function(){
    var res = {};
    var _this = this;
    if(this.typeAlert === 'confirmation'){
        res = {
            Aceptar:function(){
                if(_this.onOkHanlder){
                    _this.onOkHanlder();
                }
                    
                jQuery(_this.getId(_this.id)).dialog( "close" );
            },
            Cancelar:function(){
                jQuery(_this.getId(_this.id)).dialog( "close" );
            }
        };
    }
    else{
        console.debug(_this);
        res = {
            
            Aceptar:function(){
                if(_this.onOkHanlder){
                    _this.onOkHanlder();
                }
                    
                jQuery(_this.getId(_this.id)).dialog( "close" );
            }
        }
    }
    return res;
}

Dialog.prototype.buildContainer = function(){
    var dialogWitdh = 100;

    return '<ul id="'+this.id+'" class="rck_dialog"><li style="height:'+dialogWitdh+'px;" class="rck_dialog_icon_'+this.typeAlert+'"></li><li class="rck_dialog_content">'+this.message+'</li></ul>'
}

Dialog.prototype.create = function(cfg){
    if(!this.isCreated) this._init(cfg);
    if(this.is_empty(this.width) || this.width === "")  this.width = 400;
    if(cfg.iconCls) this.iconCls = cfg.iconCls;
    if(cfg.message) this.message = cfg.message;
    if(cfg.typeAlert) this.typeAlert = cfg.typeAlert;
    if(cfg.onOkHanlder) this.onOkHanlder = cfg.onOkHanlder;

    this.id = this.uniqueId();
    var _this = this;

    jQuery(this.buildContainer()).dialog({
        title:this.title,
        modal:true,
        maxHeight:150,
        maxWidth:500,
        open: function(event, ui) {
            jQuery(this).css({
                'max-height': 150,
                'overflow-y': 'auto'
            });
        },
        close:function(event,ui){
            jQuery(this).dialog('destroy').remove();
        },
        buttons: _this.builButtons(),
        width:this.width
    });




}

/************************************************************************************************************************/



/*
 *  Definicion de framework Rocket
 *  *************************************************************************************************************************
 **/

Rocket.Create = function(config){
    var nE;
    if(config.type!=='panel' && config.type!=='grid' && config.type!=='dialog' && config.type!=='layout'){
        nE = (new Element()).create(config);
    }
    else{
        if(config.type==='panel')   nE = (new Panel()).create(config);
        if(config.type==='grid')   nE = (new Grid()).create(config);
        if(config.type==='dialog')   nE = (new Dialog()).create(config);
        if(config.type==='layout')   nE = (new Layout()).create(config);
    }

    return nE;
};

Rocket.encode = function(object){
    return $.toJSON( object );
}

Rocket.decode = function(stringJson){
    return $.parseJSON( stringJson )
}


Rocket.Request = function(cfg){
    var http = new Request();
    http.request({
        url:cfg.url,
        method:'POST',
        data:cfg.data,
        success:function(data){
            if(cfg.beforeSuccess){
                cfg.beforeSuccess(data);
            }

            if(cfg.success){
                cfg.success(data);
            }

            if(cfg.afterSuccess){
                cfg.afterSuccess(data);
            }
        }
    });
};
